package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.EmojiFilter;
import com.ruoyi.common.utils.JedisPoolUtil;
import com.ruoyi.common.utils.SignatureUtil;
import com.ruoyi.common.utils.StringUtil;
import com.ruoyi.common.utils.oConvertUtils;
import com.ruoyi.common.utils.bean.WeixinAccount;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.SysActcode;
import com.ruoyi.system.domain.SysMenu;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysActcodeService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.web.controller.jiugongge.JiugonggeIndexController;
import com.ruoyi.framework.web.base.BaseController;

/**
 * 首页 业务处理
 * 
 * @author ruoyi
 */
@Controller
public class SysIndexController extends BaseController
{
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private ISysActcodeService actcodeService;
    
    protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(SysIndexController.class);
    
    private static final String URL = "/link?linkid=LINKID&jwid=JWID&linktype=LINKTYPE";
    private static String SIGN_KEY = "";
	private static final String SCOPE = "snsapi_userinfo"; // snsapi_userinfo
	private static final String WEB_OAUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
	private static final String REQUESTURL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	private static final String WEB_USERINFO_URL="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	
	private static String domain = "http://fc.suyongw.com";
    
    
    @GetMapping("/MP_verify_4J1fSrcH41Otr5qH.txt")
    @ResponseBody
	public String jump() {
		
		return "4J1fSrcH41Otr5qH";

	}
    
    @GetMapping("/wxact/toIndex")
	public String toIndex() {
		
		return "jiugongge";

	}
    

    @GetMapping("/toMall")
  	public String toMall() {
  		
  		return "mall";

  	}
    
    
	/**
	 * @功能 微信活动入口
	 * @时间 2019年1月25日
	 */
	@GetMapping("/wxact/{code}")
	@ResponseBody
	public Object getUrlByCode(@PathVariable("code") String code,HttpServletResponse response,HttpServletRequest request) {
		
		String fxOpenid = request.getParameter("fxOpenid");
		System.out.println(fxOpenid);
		SysActcode sysActcode = actcodeService.selectSysActcodeByCode(code);
		
		if(oConvertUtils.isEmpty(sysActcode)){
			return AjaxResult.error("活动不存在");
		}

		String url = URL.replace("LINKID",sysActcode.getLinkId()).replace("JWID",sysActcode.getJwid()).replace("LINKTYPE",sysActcode.getLinkType());
		
		if(StringUtil.notEmpty(fxOpenid)){//砍价活动
			url = url+"&fxOpenid="+fxOpenid;
		}
		
		logger.info("<--------------跳转url------->"+url);
		
		try {
			response.sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	/**
	 * @throws IOException 
	 * @功能  微信网页授权登录
	 * @时间 2019年2月15日
	 */
	@GetMapping("/link")
	public void link(HttpServletRequest request, HttpServletResponse response) throws IOException {
		long start = System.currentTimeMillis();
		logger.info("<------------开始时间戳------------>" + start);
		try {

			String linkid = request.getParameter("linkid");
			String jwid = request.getParameter("jwid");
			String linktype = request.getParameter("linktype");
			String fxOpenid = request.getParameter("fxOpenid");

			WeixinAccount weixinAccount = JedisPoolUtil.getWxAccount(jwid);

			if (weixinAccount == null) {
				logger.error("------[异常]----------OpenWX----------微信原始ID参数异常,查询公众号失败，原始ID: ------" + jwid);
				return;
			}

			String code = request.getParameter("code");
			if ((code == null) || (code.length() == 0)) {
				logger.info("<-----------距离开始时间戳耗时-------------->" + (System.currentTimeMillis() - start) + "ms");

				String REDIRECT_URI = request.getRequestURI();


				logger.info("------------------REDIRECT_URI--------1---------" + REDIRECT_URI);

				REDIRECT_URI = domain + REDIRECT_URI + "?" + request.getQueryString();

				logger.info("------------------REDIRECT_URI--------2---------" + REDIRECT_URI);

				REDIRECT_URI = URLEncoder.encode(REDIRECT_URI, "UTF-8");

				String weixinOauthURL = WEB_OAUTH_URL.replace("APPID", weixinAccount.getAccountappid())
						                             .replace("SCOPE", SCOPE)
						                             .replace("REDIRECT_URI", REDIRECT_URI);

				logger.info("------------------weixinOauthURL-----------------" + weixinOauthURL);
				logger.info("<--------------距离开始时间戳耗时------------>" + (System.currentTimeMillis() - start) + "ms");
				try {
					response.sendRedirect(weixinOauthURL);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {

				logger.info("<--------------授权回调开始-------------->" + (System.currentTimeMillis() - start));

				logger.info("<-----------------code-----------------" + code);

				String requesturl = REQUESTURL.replace("APPID", weixinAccount.getAccountappid())
						.replace("SECRET", weixinAccount.getAccountappsecret()).replace("CODE", code);

				logger.info("<-------调用微信oauth2接口获取openid请求开始-------------->" + (System.currentTimeMillis() - start)
						+ "ms");

				logger.info("<-------REQUESTURL-------------->" + requesturl);

				JSONObject json2  = HttpUtils.httpRequest(requesturl, "POST", null);

				logger.info("-------调用微信oauth2接口openid请求-------------------------->"
						+ (System.currentTimeMillis() - start) + "ms");
				
				logger.info("----------------get--json2---------------" + json2.toJSONString());
				logger.info("----------------get--access_token---------------" + json2.getString("access_token"));

				String openid = (String) json2.get("openid");
				String access_token = json2.getString("access_token");

				if ("".equals(json2.getString("openid")) || json2.getString("openid") == null) {
					try {
						throw new Exception("获取openid错误");
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
				
				//获取用户信息
				String web_userinfo_url = WEB_USERINFO_URL.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
				
				JSONObject jsonUserInfo  = HttpUtils.httpRequest(web_userinfo_url, "POST", null);
				
				logger.info("------------------用户信息--------------"+jsonUserInfo.toJSONString());
				
				logger.info("------------------用户昵称1--------------"+jsonUserInfo.getString("nickname"));
		
				String nickname = EmojiFilter.filterEmoji(jsonUserInfo.getString("nickname"));
				
				logger.info("------------------用户昵称2--------------"+nickname);
				
			
				
	            if(StringUtil.notEmpty(fxOpenid)){//跳转砍价活动界面
	            	String url = "/ACTNAME/toIndex?openid=OPENID&jwid=JWID&appid=APPID&actId=ACTID&nickname=NICKNAME&headimgurl=HEADIMGURL&fxOpenid=FX";
	            		logger.info("----------------参数linktype-----------------" + linktype);
	    				logger.info("----------------参数openid-----------------" + openid);
	    				logger.info("----------------参数 jwid-----------------" + jwid);
	    				logger.info("----------------参数linkid-----------------" + linkid);
	    				logger.info("----------------参数weixinAccount.getAccountappid()-----------------" + weixinAccount.getAccountappid());
	    				logger.info("----------------参数nickname-----------------" + nickname);
	    				logger.info("----------------参数fxOpenid-----------------" + fxOpenid);
	            	 
	 				String toIndex = url.replace("ACTNAME", linktype)
	 						            .replace("OPENID", openid)
	 						            .replace("JWID", jwid)
	 						            .replace("ACTID", linkid)
	 						            .replace("APPID",weixinAccount.getAccountappid())
	 				                    .replace("NICKNAME", URLEncoder.encode(nickname, "UTF-8"))
	 				                    .replace("HEADIMGURL", jsonUserInfo.getString("headimgurl"))
	 				                    .replace("FX", fxOpenid);
	 				                    
	 				logger.info("----------------跳转活动页面URL-----------------" + toIndex);
	 				response.sendRedirect(toIndex);
	            }else{
	            	
	            	String url = "/ACTNAME/toIndex?openid=OPENID&jwid=JWID&appid=APPID&actId=ACTID&nickname=NICKNAME&headimgurl=HEADIMGURL";
	            	
	               	logger.info("----------------参数linktype-----------------" + linktype);
	        					logger.info("----------------参数openid-----------------" + openid);
	        					logger.info("----------------参数 jwid-----------------" + jwid);
	        					logger.info("----------------参数linkid-----------------" + linkid);
	        					logger.info("----------------参数weixinAccount.getAccountappid()-----------------" + weixinAccount.getAccountappid());
	        					logger.info("----------------参数nickname-----------------" + nickname);

	 				String toIndex = url.replace("ACTNAME", linktype)
	 						            .replace("OPENID", openid)
	 						            .replace("JWID", jwid)
	 						            .replace("ACTID", linkid)
	 						            .replace("APPID",weixinAccount.getAccountappid())
	 				                    .replace("NICKNAME", URLEncoder.encode(nickname, "UTF-8"))
	 				                    .replace("HEADIMGURL", jsonUserInfo.getString("headimgurl"));
	 				logger.info("----------------跳转活动页面URL-----------------" + toIndex);
	 				response.sendRedirect(toIndex);
	            }
				
			
				
			}
		} catch (Exception localException) {
			logger.info("----------------localException-----------------" + localException);
		}
	}
	
    
    
    

    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap)
    {
        // 取身份信息
        SysUser user = getSysUser();
        // 根据用户id取出菜单
        List<SysMenu> menus = menuService.selectMenusByUser(user);
        mmap.put("menus", menus);
        mmap.put("user", user);
        System.out.println(user.getAvatar());
        mmap.put("copyrightYear", Global.getCopyrightYear());
        mmap.put("name", Global.getName());
        return "index";
    }

    // 系统介绍
    @GetMapping("/system/main")
    public String main(ModelMap mmap)
    {
        mmap.put("version", Global.getVersion());
        return "main";
    }
}
